const redis = require('redis')
const config = require("config")
const LockCache = redis.createClient({db:4,...config.get('redis')})
const {promisify} = require("util")
const get = promisify(LockCache.get).bind(LockCache)
const setnx = promisify(LockCache.setnx).bind(LockCache)
const del = promisify(LockCache.del).bind(LockCache)
const LockPrefix = 'filelock_'

export const lock = async (fileid,userid)=>{
    let result = await setnx(LockPrefix + fileid,userid)
    if(!result){
        userid = await get(LockPrefix + fileid)
        throw new Error(`file is locked by ${userid}`)
    }
}

export const unlock = async (fileid,userid)=>{
    let lock_userid = await get(LockPrefix + fileid)
    if(userid!=lock_userid){
        throw new Error(`file is locked by ${lock_userid}`)
    }
    await del(LockPrefix + fileid)
}

export const getLock = async (fileid)=>{
    let userid = await get(LockPrefix + fileid)
    return userid
}
